﻿using iAnywhere.Data.SQLAnywhere;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text; 

namespace CashAgent.Biz
{
    public class DbBase
    {
        static SAConnection conn;
        static string connStr = new SAConnectionStringBuilder()
        {
            DatabaseName = ConfigurationManager.AppSettings["DatabaseName"],
            UserID = ConfigurationManager.AppSettings["UserID"],
            Password = ConfigurationManager.AppSettings["Password"],
            ServerName = ConfigurationManager.AppSettings["ServerName"],
            Host = ConfigurationManager.AppSettings["Host"] ,
            Charset ="UTF-8"
        }.ConnectionString;


        #region 建立数据库连接
        /// <summary>
        /// 建立数据库连接
        /// </summary>
        /// <returns></returns>
        protected static SAConnection GetConn()
        { 
            conn = new SAConnection(); 
            conn.ConnectionString = connStr;
            conn.Open();
            return conn;
        }
        #endregion

        #region 关闭数据库
        /// <summary>
        /// 关闭数据库
        /// </summary>
        protected void CloseConn()
        {
            if (conn.State == ConnectionState.Open)   //判断是否打开与数据库的连接
            {
                conn.Close();   //关闭数据库的连接
                conn.Dispose();   //释放My_con变量的所有空间
            }
        }
        #endregion

        #region  创建DataTable对象
        /// <summary>
        /// 创建一个DataTable对象
        /// </summary>
        /// <param name="sqlStr">SQL语句</param>
        /// <param name="tableName">表名</param>
        /// <returns>返回DataTable对象</returns>
        protected DataTable GetDataTable(string sqlStr, string tableName, Dictionary<string, string> dicPara = null)
        {
            GetConn();   //打开与数据库的连接 
            SACommand command = new SACommand();
            command.Connection = conn;
            command.CommandText = sqlStr;
            if (dicPara != null)
            {
                foreach (string item in dicPara.Keys)
                {
                    command.Parameters.Add(item, dicPara[item]);
                }
            }

            SADataAdapter adapter = new SADataAdapter(command); 
            DataTable dt = new DataTable(tableName);
            adapter.Fill(dt);

            CloseConn();    //关闭数据库的连接
            return dt;  //返回DataTable对象的信息

        }
        #endregion
    }
}
